package com.kjs.web.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 日志aop
 * @author xuedingjiexueergou@gmail.com
 * @date 2018/10/11 17:21
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    ThreadLocal<Long> startTime = new ThreadLocal<>();


    @Pointcut("execution(public * com.kjs.web.controller..*.*(..))")
    public void logController(){}

    @Before("logController()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(returning = "ret", pointcut = "logController()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String queryString = request.getQueryString();
        // 记录下请求内容
        long spend = System.currentTimeMillis() - startTime.get();
        log.info("RemoteAddr:{}\tMethod:{}\tRequestURI:{}\tTimeConsuming:{}\tqueryString:{}\tresponseText:{}",
                request.getRemoteAddr(),
                request.getMethod(),
                request.getRequestURI(),
                spend,
                queryString,
                ret);
    }
}
